package fit.deni.hibernate;

import java.util.Collection;
import java.util.List;

import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import fit.deni.beans.Zaposleni;
import fit.deni.hibernate.interfaces.ZaposleniService;

public class ZaposleniServiceImpl implements ZaposleniService {
	private Session session;

	public ZaposleniServiceImpl(Session session) {
		this.session = session;
	}

	public Zaposleni getUserByUsername(String username) {
		List<Zaposleni> results = session.createCriteria(Zaposleni.class)
			.add(Restrictions.eq("deleted", false))
			.add(Restrictions.eq("username", username)).list();
		if (results.size() < 1)
			return null;
		else
			return results.get(0);
	}

	@CommitAfter
	public void addUser(Zaposleni korisnik) {
		session.merge(korisnik);
	}

	@CommitAfter
	public void deleteUser(Zaposleni korisnik) {
		korisnik.setDeleted(true);
		session.merge(korisnik);
//		session.delete(korisnik);
//		session.flush();
	}

	public Collection<Zaposleni> getAdminitrators() {
		List<Zaposleni> results = session.createCriteria(Zaposleni.class)
			.add(Restrictions.eq("deleted", false))
			.add(Restrictions.eq("role", Zaposleni.ADMINISTRATOR)).list();
		return results;
	}
}
